package cn.com.dhc.danlu.activity.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.category.GoodInfoSearchActivity;
import cn.com.dhc.danlu.activity.home.presenter.HomeContract;
import cn.com.dhc.danlu.activity.home.presenter.HomeContract.IHomeView;
import cn.com.dhc.danlu.activity.home.presenter.HomePresenter;
import cn.com.dhc.danlu.activity.home.wrap.CategoryHolder;
import cn.com.dhc.danlu.activity.home.wrap.HomeTopHolder;
import cn.com.dhc.danlu.activity.home.wrap.HomeViewModule;
import cn.com.dhc.danlu.activity.message.MessageContainerActivity;
import cn.com.dhc.danlu.model.bus.MsgEvent;
import cn.com.dhc.danlu.model.bus.MsgEvent.MsgType;
import cn.com.dhc.danlu.receiver.network.ConnectedState;
import cn.com.dhc.danlu.receiver.network.NetworkReceiver;
import cn.com.dhc.danlu.receiver.network.NetworkStateCallback;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.widget.GradationScrollView;
import cn.com.dhc.danlu.widget.adapter.GeneralGoodsAdapter;
import cn.com.dhc.danlu.widget.home.HeaderView;
import cn.com.dhc.danlu.widget.home.HomeListView;
import cn.com.dhc.danlu.widget.loadlayer.LayerEnum;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.hd.mall.web.webservices.entity.response.common.GetBannerListResponse;
import cn.com.hd.mall.web.webservices.entity.response.common.GetTopicListResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.PromotionListResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.RecommendListResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author wuhaiyang
 */

public class HomeActivity extends BaseActivity implements IHomeView, NetworkStateCallback {
    /**
     * net 异步任务 中间件
     */
    private HomePresenter mHomePresenter;

    //顶部搜索分类消息视图封装
    private HomeTopHolder mHomeTopHolder;
    //顶部各个模块视图封装
    private HomeViewModule mHomeViewModule;

    private CategoryHolder mCategoryHolder;

    // loadding 视图层
    private LoaddingLayout mLoaddingLayout;

    // 2016/8/4 两个Headerview
    private HeaderView mPromotionHeaderView; // 丹露促销
    private HeaderView mRecommenedHeaderView; // 丹露推荐

    // 2016/8/4 两个listView
    private HomeListView mPromotionListView; //丹露促销
    private HomeListView mRecommendListView; //丹露推荐

    private GeneralGoodsAdapter mPromotionAdapter;
    private GeneralGoodsAdapter mRecommendAdapter;

    private GradationScrollView mGradationScrollView;

    private LinearLayout categoryLinear;

    /**
     * 网络状况监听器
     */
    private NetworkReceiver netReceiver;

    /**
     * 刷新未读消息数量
     */
    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void onUserEvent(MsgEvent event) {
        MsgType type = event.getType();
        String from = event.getEventFrom();
        if (from.equals(CommonConst.PushMsgFrom._FROM_PUSH_RECEIVER)) {
            if (null != mHomePresenter) {
                mHomePresenter.getUnreadMsgCountRequest();
            }
        }
    }
    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void refreshBadgeCount(HomeContract.MsgCountType type, int count) {
        if (type == HomeContract.MsgCountType.push_msg) {
            // 推送消息
            mHomeTopHolder.refreshMsgCount(count);
        }  else if (type == HomeContract.MsgCountType.order) {
            //订单角标数量
            mHomeViewModule.refreshTypeBadge(true, count);
        }
    }

    @Override
    public void switchLayer(LayerEnum layerEnum, @Nullable String info) {
        if (layerEnum == LayerEnum.layer_error) {
            mLoaddingLayout.showErrorView(!TextUtils.isEmpty(info) ? info : "请求失败");
        } else if (layerEnum == LayerEnum.layer_success) {
            mLoaddingLayout.showContentView();
        } else if (layerEnum == LayerEnum.layyer_loading) {
            mLoaddingLayout.showLoaddingView();
        }
    }

    @Override
    public void refreshTopicList(GetTopicListResponse model) {
        mHomeViewModule.refreshTypeSource(model.getTopicList());
    }

    @Override
    public void refreshViewModule(List<GetBannerListResponse.BannerListModel> mTopBanners, boolean isBanner) {
        if (isBanner) {
            mHomeViewModule.refreshBanner(mTopBanners);
        } else {
            mHomeViewModule.refreshAdvertisment(mTopBanners.get(0));
        }
    }

    @Override
    public void setPromotionList(PromotionListResponse model, int totalCount) {
        mPromotionHeaderView.stopRefresh();
        refreshMerchListView(mPromotionListView, model.getPromotionListModel(), totalCount, true);
    }

    @Override
    public void setRecommendList(RecommendListResponse model, int totalCount) {
        mRecommenedHeaderView.stopRefresh();
        refreshMerchListView(mRecommendListView, model.getRecommendListModel(), totalCount, false);
    }

    @Override
    public void getMerchListError(boolean isPromotion, String info) {
        if (isPromotion) {
            mPromotionHeaderView.stopRefresh();
        } else {
            mRecommenedHeaderView.stopRefresh();
        }
    }

    @Override
    public void showRotateBar(boolean isPromotion) {
        if (isPromotion) {
            mPromotionHeaderView.startRefresh();
        } else {
            mRecommenedHeaderView.startRefresh();
        }
    }

    /****
     * presenter callback
     **/
    private void refreshMerchListView(HomeListView listView, List datas, int totalCount, boolean isPromotion) {
        //隐藏emptyView
        if (isPromotion) {
            if (null == mPromotionAdapter) {
                mPromotionAdapter = new GeneralGoodsAdapter(this, GeneralGoodsAdapter.ListType.sale_promotion);
            }
            mPromotionAdapter.refreshData(datas);
            mPromotionListView.refreshView(mPromotionAdapter);
        } else {
            if (null == mRecommendAdapter) {
                mRecommendAdapter = new GeneralGoodsAdapter(this, GeneralGoodsAdapter.ListType.recommended);
            }
            mRecommendAdapter.refreshData(datas);
            mRecommendListView.refreshView(mRecommendAdapter);
        }

        if (datas == null || datas.isEmpty()) {
            //空
            if (isPromotion) {
                mPromotionHeaderView.setVisibility(View.GONE);
            } else {
                mRecommenedHeaderView.setVisibility(View.GONE);
            }
            listView.setVisibility(View.GONE);
        } else {
            if (isPromotion) {
                mPromotionHeaderView.setVisibility(View.VISIBLE);
                mPromotionHeaderView.isShowRefresh(totalCount > 4);
            } else {
                mRecommenedHeaderView.setVisibility(View.VISIBLE);
                mRecommenedHeaderView.isShowRefresh(totalCount > 4);
            }
            listView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        initView();
        mHomePresenter = new HomePresenter();
        mHomePresenter.attachView(this);
        mLoaddingLayout.setRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLoadData();
            }
        });
        startLoadData();
        EventBus.getDefault().register(this);
        // 网络状况注册
        IntentFilter netFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        netReceiver = new NetworkReceiver();
        registerReceiver(netReceiver, netFilter);
        NetworkReceiver.mListener.add(this);

        bindHeader();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        mHomePresenter.detachView();
        mHomePresenter = null;
        NetworkReceiver.mListener.remove(this);
        unregisterReceiver(netReceiver);
        super.onDestroy();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }


    @Override
    protected void onResume() {
        mHomePresenter.onStart();
        if (mCategoryHolder.isShowing()) {
            mCategoryHolder.hide();
        }

        super.onResume();
    }

    private void bindHeader() {

        mPromotionHeaderView.setIvReplace(R.drawable.ic_header_home_cuxiao);
        mRecommenedHeaderView.setIvReplace(R.drawable.ic_header_home_tuijian);
        mPromotionHeaderView.setOnRefreshViewCickListener(new OnChangeMerchListListener(true));
        mRecommenedHeaderView.setOnRefreshViewCickListener(new OnChangeMerchListListener(false));
        mGradationScrollView.setScrollViewListener(new GradationScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
                mHomeTopHolder.changeHeaderbg(x, y, oldx, oldy);
            }
        });
    }

    public void startLoadData() {
        mLoaddingLayout.showLoaddingView();

        mHomePresenter.fetchTypeDatas();
    }

    private void initView() {
        mLoaddingLayout = (LoaddingLayout) findViewById(R.id.ll_layer);
        mHomeTopHolder = new HomeTopHolder(findViewById(R.id.rl_home_top));
        mHomeViewModule = new HomeViewModule(findViewById(R.id.ll_home_container));

        //        mCategoryHolder = new CategoryHolder(this, danluTaskProxy);
        mCategoryHolder = new CategoryHolder(this);

        mPromotionListView = (HomeListView) findViewById(R.id.promotion_listview);
        mRecommendListView = (HomeListView) findViewById(R.id.recommended_listview);

        mGradationScrollView = (GradationScrollView) findViewById(R.id.gsc_scrollview);
        mPromotionHeaderView = (HeaderView) findViewById(R.id.hv_promotion);
        mRecommenedHeaderView = (HeaderView) findViewById(R.id.hv_recomended);

        mHomeTopHolder.setOnOptionClickListener(new HomeTopHolder.OnOptionClickListener() {
            @Override
            public void clickOption(View v, int optionId) {
                switch (optionId) {
                    case HomeTopHolder.CLASSIFY:  // 点击分类
                        mCategoryHolder.toggleCategoryPanel(v);
                        break;
                    case HomeTopHolder.MSG: //点击消息图标
                        Intent intent = new Intent(getContext(), MessageContainerActivity.class);
                        getContext().startActivity(intent);
                        break;
                    case HomeTopHolder.SEARCH: //点击搜索图标
                        // 跳转到搜索界面
                        Intent searchIntent = new Intent(getContext(), GoodInfoSearchActivity.class);
                        // 跳转到搜索界面
                        ((Activity) getContext()).startActivityForResult(searchIntent, 2);
                        break;
                }
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        CommonUtils.hideSoftInputForce(this);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK) {
            data.putExtra(CommonConst.IntentKey.SEARCH_RANGE_KEY, true);
            EventBus.getDefault().post(data);
        }
    }

    @Override
    public void onConnected(ConnectedState type) {
        switch (type) {
            case TYPE_MOBILE: // 移动网络
                agent.setWifi(false);
                break;

            case TYPE_WIFI: // wifi网络
                agent.setWifi(true);
                break;
        }
    }

    @Override
    public void onDisconnected() {
        // 失去连接
    }

    private class OnChangeMerchListListener implements HeaderView.OnRefreshViewCickListener {
        private boolean isPromotion;

        OnChangeMerchListListener(boolean isPromotion) {
            this.isPromotion = isPromotion;
        }

        @Override
        public void onClick(View v) {
            mHomePresenter.refreshMerchList(isPromotion);
        }
    }
}